﻿//------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="Robert MacLean">
//      Copyright © Robert MacLean.  All Rights Reserved.
// </copyright>
//
//  Details on this see: http://pepper.codeplex.com
//  This code released under the terms of the 
//  Microsoft Public License  (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//------------------------------------------------------------------------------

namespace Pepper.Forms
{
    using System;
    using System.Windows.Input;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Threading;
    using System.Windows;
    using Microsoft.WindowsAPICodePack.Dialogs;
    using Pepper.Core;
    using System.Threading.Tasks;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private readonly static Properties.Settings appSettings = Pepper.Forms.Properties.Settings.Default;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void LoadSettings(Guid userId, string password)
        {
            var syncContext = SynchronizationContext.Current;
            string downloadedSettings = string.Empty;
            {
                var marqueeWindow = new Marquee { Owner = this };

                marqueeWindow.Loaded += (ms, me) =>
                {
                    Task.Factory.StartNew(() =>
                    {
                        downloadedSettings = Settings.DownloadSettings(userId, password);
                        syncContext.Send(state => { marqueeWindow.Close(); }, null);
                    });
                };

                marqueeWindow.ShowDialog();
            }

            if (!string.IsNullOrEmpty(downloadedSettings))
            {
                using (var taskDialog = new TaskDialog()
                {
                    Caption = "Pepper",
                    Cancelable = true,
                    Icon = TaskDialogStandardIcon.None,
                    StartupLocation = TaskDialogStartupLocation.CenterOwner,
                    InstructionText = "We have retrieved your settings, what would you like to do with them?",
                    Text =
    @"'Import Now': will import settings immediately into Visual Studio. 
   Note this can take a few minutes and will restart Visual Studio.

'Save to disk': will save the settings to a file on your desktop.
'Cancel': will not do anything."
                })
                {
                    var importButton = new TaskDialogButton("importButton", "Import Now")
                    {
                        Default = true
                    };

                    importButton.Click += (sender, e) =>
                        {
                            taskDialog.Close();
                            var filePath = Path.GetTempFileName();
                            try
                            {
                                var marqueeWindow = new Marquee() { Owner = this };
                                marqueeWindow.Loaded += (msender, me) =>
                                {
                                    var thread = new Thread(() =>
                                    {
                                        File.WriteAllText(filePath, downloadedSettings);
                                        Settings.ImportVisualStudioSettings(filePath);
                                        syncContext.Send(state => { marqueeWindow.Close(); }, null);
                                    });

                                    thread.SetApartmentState(ApartmentState.STA);
                                    thread.Start();
                                };

                                marqueeWindow.ShowDialog();
                            }
                            finally
                            {
                                File.Delete(filePath);
                            }
                        };

                    var saveSettingsButton = new TaskDialogButton("saveButton", "Save to disk");
                    saveSettingsButton.Click += (sender, e) =>
                        {
                            taskDialog.Close();
                            var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), string.Format(CultureInfo.CurrentCulture, "Your Visual Studio Settings ({0:dd-MM-yyyy hh-mm}).vssettings", DateTime.Now));
                            File.WriteAllText(filePath, downloadedSettings);
                        };

                    var cancelButton = new TaskDialogButton("cancelButton", "Cancel");
                    cancelButton.Click += (sender, e) =>
                        {
                            taskDialog.Close();
                        };

                    taskDialog.Controls.Add(importButton);
                    taskDialog.Controls.Add(saveSettingsButton);
                    taskDialog.Controls.Add(cancelButton);

                    taskDialog.Show();
                };
            }
        }

        private void LoadSettingsClick(object sender, RoutedEventArgs e)
        {
            CommonErrorHandler(() =>
                {
                    var details = Setup();
                    if (details == null)
                    {
                        return;
                    }

                    LoadSettings(details.UserId, details.Password);
                    this.Close();
                });
        }

        private static UserDetails Setup()
        {
            UserDetails result = null;

            if (appSettings.FirstRun)
            {
                MessageBox.Show(@"You will be presented with a login dialog box next. 
If you have previously used Pepper please enter the email address & password you used previously.
If this is your first time, please enter your email address & password and we will automatically create an account for you.",
                    "It looks like your first time with Pepper", MessageBoxButton.OK, MessageBoxImage.Information);

                appSettings.FirstRun = false;
                appSettings.Save();
            }

            var credentials = AuthenticationPrompt.PromptForPassword();
            if (!string.IsNullOrWhiteSpace(credentials.Item1))
            {
                CommonErrorHandler(() =>
                    {
                        var userId = Settings.Login(credentials.Item1, credentials.Item2);
                        result = new UserDetails(userId, credentials.Item2);
                    });
            }

            return result;
        }

        private static void CommonErrorHandler(Action action)
        {
            try
            {
                action();
            }
            catch (PepperCoreException err)
            {
                using (var taskDialog = new TaskDialog()
                {
                    Caption = "Pepper",
                    Text = err.Message,
                    StartupLocation = TaskDialogStartupLocation.CenterOwner
                })
                {
                    taskDialog.Show();
                }
            }
            catch (Exception err)
            {
                using (var taskDialog = new TaskDialog()
                {
                    Caption = "An exception occurred in Pepper",
                    Text = "This dialog has information which may diagnose and resolve the issue",
                    StartupLocation = TaskDialogStartupLocation.CenterOwner,
                    DetailsExpanded = true,
                    DetailsExpandedText = err.ToString()
                })
                {
                    taskDialog.Show();
                }

                throw;
            }
        }

        private void SaveSettingsClick(object sender, RoutedEventArgs e)
        {
            CommonErrorHandler(() =>
            {
                var details = Setup();
                if (details == null)
                {
                    return;
                }

                var syncContext = SynchronizationContext.Current;
                var marqueeWindow = new Marquee { Owner = this };

                marqueeWindow.Loaded += (ms, me) =>
                {
                    Task.Factory.StartNew(() =>
                        {
                            Settings.SaveSettings(details.UserId, details.Password);
                            syncContext.Send(state => { marqueeWindow.Close(); }, null);
                        });
                };

                marqueeWindow.ShowDialog();
                this.Close();
            });
        }

        private void SADevNavigateClick(object sender, MouseButtonEventArgs e)
        {
            Process.Start("http://www.sadev.co.za");
        }

        private void AzureNavigateClick(object sender, MouseButtonEventArgs e)
        {
            Process.Start("http://windows.azure.com/");
        }

        private void SADevRSSNavigateClick(object sender, MouseButtonEventArgs e)
        {
            Process.Start("http://www.sadev.co.za/rss.xml");
        }

        private void TwitterNavigateClick(object sender, MouseButtonEventArgs e)
        {
            Process.Start("http://www.twitter.com/rmaclean");
        }
    }
}
